<template>
  <el-card shadow="hover" style="margin: 20px;height: 70px">
    <el-form label-width="100px">
      <el-row :gutter="10">
        <el-col :span="5">
          <el-form-item label="申请单号">
            <el-input v-model="searchForm.applyNumber" placeholder="请输入申请单号"/>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="申请人姓名">
            <el-input v-model="searchForm.username" placeholder="请输入申请人姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="申请单状态">
            <el-select v-model="searchForm.status" placeholder="请选择申请单状态">
              <el-option v-for="item in applyStatusList"
                         :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="申请类型">
            <el-select v-model="searchForm.type" placeholder="请选择申请类型">
              <el-option v-for="item in applyTypeList"
                         :label="item.label"
                         :value="item.value"/>

            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>

  <el-card style="margin: 20px;height: 730px">
    <div style="margin:10px 0 40px 10px;">
      申请列表
      <div style="float: right">
        <el-button type="success" @click="buttonCont">添加申请</el-button>
        <el-button type="primary" @click="exportApplication">导出信息</el-button>
      </div>
    </div>
    <el-table ref="multipleTableRef"
              :data="paginatedData" stripe
              style="margin-top: 20px;height: 560px">
      <el-table-column type="index" label="编号" width="80" align="center"/>
      <el-table-column label="申请单号" prop="applyNumber" align="center"/>
      <el-table-column label="申请人姓名" prop="username" align="center"/>
      <el-table-column label="手机号" prop="phone" width="110" align="center"/>
      <el-table-column label="部门所属" prop="department" align="center"
                       :formatter="departmentFormatter"/>
      <el-table-column label="申请类型" prop="type" align="center"
                       :formatter="applyTypeFormatter"/>
      <el-table-column label="申请状态" prop="status" align="center"
                       :formatter="applyStatusFormatter"/>
      <el-table-column label="操作" width="280px" align="center">
        <template #default="scope">
          <el-button link type="primary"
                     v-if="scope.row.type === 'busrequire'"
                     @click="busrequire(scope.row.id)">
            查看车辆详情</el-button>
          <el-button link type="primary"
                     @click="cancelApplication(scope.row.id)"
                     :disabled="scope.row.status!=10">
            撤销申请
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableData.length"
        @current-change="handlePageChange"
        style="margin-top:20px;margin-left:  35%"
    />

  </el-card>

  <!-- 车辆审批/查看弹窗 -->
  <el-dialog title="查看详情"
             :width="800"
             style="padding: 40px"
             v-model="busrequireVisible">
    <el-descriptions direction="horizontal" :column="2" border>
      <el-descriptions-item label="申请人">{{ busrequireData.username }}</el-descriptions-item>
      <el-descriptions-item label="申请人手机号">{{ busrequireData.phone }}</el-descriptions-item>
      <el-descriptions-item label="申请人邮箱">{{ busrequireData.email }}</el-descriptions-item>
      <el-descriptions-item label="申请人部门">
        {{ departmentFormatter(busrequireData,null,busrequireData.department) }}
      </el-descriptions-item>
      <el-descriptions-item label="使用开始时间">{{ busrequireData.startTime }}</el-descriptions-item>
      <el-descriptions-item label="使用结束时间">{{ busrequireData.endTime }}</el-descriptions-item>
      <el-descriptions-item label="车辆出发地">{{ busrequireData.startPoint }}</el-descriptions-item>
      <el-descriptions-item label="车辆目的地">{{ busrequireData.endPoint }}</el-descriptions-item>
      <el-descriptions-item label="申请原因">{{ busrequireData.reason }}</el-descriptions-item>
      <el-descriptions-item label="申请时间">{{ busrequireData.createTime }}</el-descriptions-item>
      <!--  驳回原因要在点击驳回才显示 -->
      <el-descriptions-item label="驳回原因" v-if="busrequireData.status==40">
        {{busrequireData.rejectReason}}
      </el-descriptions-item>
    </el-descriptions>
  </el-dialog>

</template>

<script setup>
import router from "@/router";
import {computed, onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import * as XLSX from "xlsx";


const applyStatusList = ref([]);
const applyTypeList = ref([]);
const departmentList = ref([]);
onMounted(() => {
  loadDictOptions(applyStatusList, 'applyStatus');
  loadDictOptions(applyTypeList, 'applyType')
  loadDictOptions(departmentList, 'department')
});
const applyStatusFormatter = (row, column, cellValue, index) => {
  if (!applyStatusList.value) {
    return cellValue;
  }
  for (let item of applyStatusList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
};
const applyTypeFormatter = (row, column, cellValue, index) => {
  if (!applyTypeList.value) {
    return cellValue;
  }
  for (let item of applyTypeList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
};
const departmentFormatter = (row, column, cellValue, index) => {
  if (!departmentList.value) {
    return cellValue;
  }
  for (let item of departmentList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
};
const tableData = ref([]);
const currentPage = ref(1);// 默认显示页码
const pageSize = ref(10); // 每页显示6条


// 计算当前页面的数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return tableData.value.slice(offset, offset + pageSize.value);
});
// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
const searchForm = ref({
  applyNumber: "",
  username: "",
  status: "",
  type: ""
});
const search = () => {
  let data = qs.stringify(searchForm.value);
  axios.get(BASE_URL + "/v1/application/select?" + data)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
onMounted(() => {
  search();
});
const resetSearch = () => {
  searchForm.value = {};
  search();
}
const exportApplication = async () => {
  search();
  try {
    // 定义固定的表头
    const headers = [
      'id', 'apply_id', 'applyNumber', 'user_id', 'username',
      'phone', 'email', 'department', 'type',
      'status', 'createTime'
    ];

    // 将 JSON 数据转换为二维数组
    const data = tableData.value.map(application => headers.map(header => application[header]));

    // 检查数据有效性
    if (!data.length || !data.every(row => Array.isArray(row) && row.length === headers.length)) {
      errorInfo('导出失败：数据为空');
      return;
    }

    // 直接在数据前插入表头
    data.unshift(headers);

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // 动态生成文件名
    // 获取当前日期并格式化为 YYYY_MM_DD 格式
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
    const day = String(now.getDate()).padStart(2, '0');

    const formattedDate = `${year}_${month}_${day}`;
    const fileName = `application_export_${formattedDate}.xlsx`;

    // 导出Excel文件
    XLSX.writeFile(wb, fileName);

    // 提示用户导出成功
    OKInfo('导出成功');
  } catch (error) {
    errorInfo('导出失败，请检查控制台日志');
  }
};

const buttonCont = () => {
  router.push('/apply')
}

const cancelApplication = (id) => {
  ElMessageBox.confirm('确定撤销申请吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
        axios.put(BASE_URL + '/v1/application/cancel/' + id)
            .then((response) => {
              if (response.data.code === 2000) {
                OKInfo('撤销成功')
                search();
              } else {
                ElMessage({
                  message: response.data.msg,
                  type: 'error',
                })
              }
            })
      })
}
const busrequireVisible = ref(false);
const busrequireData = ref({});
const busrequire = (id) => {
  busrequireVisible.value = true;
  axios.get(BASE_URL + '/v1/application/select/busrequire/' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          busrequireData.value = response.data.data[0];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })
}
</script>

<style scoped>

</style>